#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/stat.h>

#define BUF_SIZE 256
#define PROJ_ID 32
#define PATH_NAME "/tmp"
#define SERVER_MSG 1
#define CLIENT_MSG 2

int main(int argc, char const *argv[])
{
    // 用户自定义消息缓冲区
    struct mymsgbuf {
        long msgtype;
        char ctrlstring[BUF_SIZE];
    } msgbuffer;

    int qid; // 消息队列标识符
    int msglen; 
    key_t msgkey;

    // 创建一个键 用于创建消息队列
    if ((msgkey = ftok(PATH_NAME, PROJ_ID)) == -1 ) {
        perror("ftok error!\n");
        exit(1);
    }

    // 创建一个新的消息队列
    if ((qid = msgget(msgkey, IPC_CREAT|0660)) == -1) {
        perror("msgget error!\n");
        exit(1);
    }

    while (1) {
        printf("Server: ");
        // 等待用户输入
        fgets(msgbuffer.ctrlstring, BUF_SIZE, stdin);
        if (strncmp("exit", msgbuffer.ctrlstring, 4) == 0) {
            msgctl(qid, IPC_RMID, NULL);// 设置消息队列属性为删除
            break;
        }
        msgbuffer.ctrlstring[strlen(msgbuffer.ctrlstring)-1] = '\0';
        msgbuffer.msgtype = SERVER_MSG;
        // 发送消息
        if (msgsnd(qid, &msgbuffer, strlen(msgbuffer.ctrlstring)+1, 0) == -1) {
            perror("Server msgsnd error!\n");
            exit(1);
        }
        // 从client接收消息
        if (msgrcv(qid, &msgbuffer, BUF_SIZE, CLIENT_MSG, 0) == -1) {
            perror("Server msgrcv error!\n");
            exit(1);
        }
        printf("Client: %s\n", msgbuffer.ctrlstring);

    }
    exit(0);

    return 0;
}
